package com.easymin.weixin.controller.v5;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.api.DaijiaApi;
import com.easymin.weixin.controller.v5.utils.ErrorMapV5;
import com.easymin.weixin.controller.v5.utils.ResultV5;
import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.manager.WxApplicationManager;
import com.google.common.base.Preconditions;

/**
 * 微信公众号广告数据请求
 * @author Administrator
 *
 */
@Controller
@RequestMapping("v5/news/")
public class NewsController {
	
	@Autowired
	private DaijiaApi daijiaApi;
	@Autowired
	private WxApplicationManager wxApplicationManager;
	
	
	/**
	 * 获取首页广告位
	 * @param appKey 系统key
	 * @param lat
	 * @param lng
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "homeAdv", method = {RequestMethod.GET})
	public ResultV5 homeAdv (
			@RequestParam("appKey") String appKey,
		    @RequestParam("companyId") Long companyId) {

		WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
		Preconditions.checkArgument(null != wxApplication, "appKey错误");

		Map<String, Object> dataMap = new HashMap<String, Object>();
		JSONObject jsonObject = daijiaApi.getHomeAdv(wxApplication.getAddress(), companyId, "weixin");
		
		ResultV5 result = null;
		
		if (null != jsonObject && jsonObject.getInteger("code") == 0) {
			result = ErrorMapV5.ERR_SUCCESS.clone();
			JSONObject data = jsonObject.getJSONObject("data");
			if (data != null) {
				dataMap.put("upAdvs", data.getJSONArray("upAdvs"));
				dataMap.put("downAdvs", data.getJSONArray("downAdvs"));
			}
		}  else {
			result = ErrorMapV5.ERR_SYSTEM;
		}
		result.setData(dataMap);
		return result;
	}
	
	
}
